#!/bin/bash
##master节点一键配置
ver=`kubeadm version|awk '{print $5}'|sed "s/[^0-9|\.]//g"|awk 'NR==1{print}'`
hostnames=`hostname`
ip=`cat /etc/hosts|grep "$hostnames" | awk '{print $1}'|awk 'NR==1{print}'`
init_k8s(){
	echo '按回车开始初始化master节点'
	sudo systemctl stop firewalld&&sudo systemctl disable firewalld
	sudo swapoff -a
	sudo sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab 
	sudo systemctl enable docker kubelet 
	if [[ "$ip" == "127.0.0.1" ]];then
		echo '请输入本机固定IP进行初始化服务'
		read ip
	else
		echo -e "将使用${ip}作为服务管理IP\n请确保此IP为静态IP\n若不是请输入 r 重新设置管理IP\n按回车继续"
		read res
		if [[ "$res" == "r" ]];then
			echo '请输入本机固定IP进行初始化服务'
			read ip
		else
			echo '将使用此ip进行初始化服务'
		fi
	fi
	echo -e "${ip} ${hostnames}" >> /etc/hosts
	kubeadm init --apiserver-advertise-address=${ip} \
    --image-repository registry.aliyuncs.com/google_containers \
    --kubernetes-version v${ver} \
    --service-cidr=10.1.0.0/16 \
    --pod-network-cidr=10.244.0.0/16
	if [[ "$?" == "0" ]];then
		echo '初始化完成第一部分'
		rm -rf $HOME/.kube
		sudo mkdir -p $HOME/.kube
		sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
		sudo chown $(id -u):$(id -g) $HOME/.kube/config
		sudo kubectl apply -f https://xypj-1252147235.cos.ap-guangzhou.myqcloud.com/kube-flannel.yaml
		if [[ "$?" == "0" ]];then
			echo -e "执行此命令可获取注册URL\nkubeadm token create --print-join-command"
		else
			echo -e "创建pod失败\n请检查网络或系统"
		fi
	else	
		echo '初始化失败,请检查主机名是否有特殊字符'
		exit 1
	fi
}
chek_service(){
	sudo systemctl daemon-reload
	sudo systemctl restart docker kubelet
	if [[ "$?" == "0" ]];then
		echo '服务启动成功'
		init_k8s
	else
		echo '相关服务启动失败'
		exit 1
	fi
}
chek_service
